package com.cheap.search.task.one;

import com.cheap.common.dto.PageDTO;
import com.cheap.common.feignapi.ItemServiceApi;
import com.cheap.common.pojo.po.Item;
import com.cheap.search.es.mapper.EsItemMapper;
import com.cheap.search.es.pojo.ItemDoc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;

import java.util.ArrayList;
import java.util.List;

/**
 * 全量同步帖子到 es
 */
// todo 取消注释开启任务
//@Component
@Slf4j
public class FullSyncItemToEs implements CommandLineRunner {

    private static final int FIRST_PAGE_INDEX = 1;
    public static final int ONE_PAGE_SIZE = 500;

    @Autowired
    private EsItemMapper esItemMapper;
    @Autowired
    private ItemServiceApi itemServiceApi;


    @Override
    public void run(String... args) {

        PageDTO<Item> itemPageDTO = itemServiceApi.getListByPage(FIRST_PAGE_INDEX, ONE_PAGE_SIZE);
        // 获取页数，去做更新
        int pageSize = itemPageDTO.getPageSize().intValue();
//        List<ItemDoc> docListFirst = getToDocList(itemPageDTO.getList());
        toESData(1, pageSize);
    }

    /**
     * 真正的去同步数据
     */
    private void toESData(Integer startPage, Integer endPage) {
        for (int i = startPage; i <= endPage; i++){
            PageDTO<Item> dataDTO = itemServiceApi.getListByPage(i, ONE_PAGE_SIZE);
            List<ItemDoc> toDocList = getToDocList(dataDTO.getList());
            esItemMapper.insertBatch(toDocList);
        }
    }

    /**
     * 开启并行流快速转化数据
     */
    private List<ItemDoc> getToDocList(List<Item> list) {
        List<ItemDoc> itemDocs = new ArrayList<>();
        list.stream().parallel()
                .forEach(one ->{
                    ItemDoc itemDoc = new ItemDoc(one);
                    itemDocs.add(itemDoc);
                        });
        return itemDocs;
    }
}
